

window.mobileAgent = window.mobileAgent || {};

(function (mobileAgent, window) {
    var _postMessage = function (action, params, callBack) {
        var json  = JSON.stringify({
                                action : action,
                                params : params,
                                callBack : callBack
                            });
        //Android环境
        if(typeof window.mobileAgent != "undefined" && typeof window.mobileAgent.postMessage != "undefined"){
            window.mobileAgent.postMessage(json);
            return;
        }
        //iOS环境
        if(typeof window.webkit != "undefined" && typeof window.webkit.messageHandlers != "undefined" && typeof window.webkit.messageHandlers.iOSAgent != "undefined"){
            window.webkit.messageHandlers.iOSAgent.postMessage(json);
        }
    };

    //是否运行在app环境
    mobileAgent.isRunOnApp = function(){
        if(typeof window.mobileAgent != "undefined"
                        && typeof window.mobileAgent.postMessage != "undefined"){
                    return true;
                }

        if(typeof window.webkit != "undefined"
                        && typeof window.webkit.messageHandlers != "undefined"
                        && typeof window.webkit.messageHandlers.iOSAgent != "undefined"){
                    return true;
                }
        return false;
    };

    /**
     * @description: 关闭窗口。仅在系统导航栏隐藏时需要JS触发此方法。
     * @param {type} 无
     * @return: 无
     */
    mobileAgent.closeWindow = function () {
        _postMessage('close');
    };

    /**
     * @description: 微信分享方式
     * @param {type}
     * @return:
     */
    var WechatShareType = {
        UNSELECTED:0,//未指定，此时会先让弹出分享方式选择框让用户选择
        SESSION:1,//好友
        TIME_LINE:2//朋友圈
    };

    /**
     * @description: 微信分享，支持分享给好友和分享到朋友圈
     * @param {title}:标题
     * @pararm {content}:内容简述
     * @param {imagePath}:缩略图URL
     * @param {url}:网页URL
     * @param {shareType}:分享方式，如WechatShareType.UNSELECTED等
     * @param {callBack}:分享结束的回调函数，参数个数：1，类型：整数（0：失败，1：成功）
     * @return: 无
     */
    mobileAgent.wechatShare = function (title, content, imagePath, url,shareType,callBack) {
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            'share',
            {
                title: title, content: content, imagePath: imagePath, url: url,shareType:shareType
            },
            callBackMethodName
        );
    };



    /**
     * @description: 打开(新H5页面在)新窗口。
     * @param {url}:H5页面链接，远程或本地皆可。
     * @param {title}:页面标题，用于显示在Native窗口的标题栏上。
     * @return: 无
     */
    mobileAgent.openNewWindow = function(url,title){
        _postMessage(
            'openNewWindow',
            {
                url:url,
                title:title
            }
        );
    };

    /**
     * @description: 跳转到Native页面。
     * @param {pageName}:Native页面名称。
     * @param {arguments}:Native页面所需参数，Object类型。
     * @return:
     */
    mobileAgent.goPage = function(pageName,arguments){
        _postMessage(
            'goPage',
            {
                pageName:pageName,
                arguments:arguments
            }
        );
    };

    /**
     * @description: 友盟事件统计
     * @param {eventName}:事件描述
     * @param {eventId}:事件ID
     * @return: 无
     */
    mobileAgent.onUmengEvent = function(eventId,eventName){
        _postMessage(
            'umengEvent',
            {
                eventId:eventId,
                eventName:eventName
            }
        );
    };

    /**
     * @description: 退出登录
     * @param {type}
     * @return:
     */
    mobileAgent.logout = function () {
        _postMessage('logout');
    };


    /**
     * @description: 页面截图区域
     * @param {left}:左边距,数值为百分比
     * @param {top}:上边距,数值为百分比
     * @param {width}:宽度,数值为百分比
     * @param {height}:高度,数值为百分比
     * @return:
     */
    var ScreenshotMargin = {
        left:0.0,
        top:0.0,
        width:1.0,
        height:1.0
    };
    /**
     * @description: 截图当前页面并保存进相册，支持截取页面部分区域
     * @param {callBack}:回调函数
     * @param {margin}: ScreenshotMargin对象
     * @return: 无
     */
     mobileAgent.screenshot2PhotoAlbum = function(callBack,margin){
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            'screenshot2PhotoAlbum',
            {
                margin: margin
            },
            callBackMethodName
        );
     };

    /**
     * @description: 获取view坐标
     * @param {callBack}:回调函数
     * @param {margin}: ScreenshotMargin对象
     * @return: 无
     */
    mobileAgent.viewlocation = function(callBack,margin){
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            'viewlocation',
            {
                margin: margin
            },
            callBackMethodName
        );
    };


    /**
     * @description: 中寰事件统计
     * @param {eventId}:事件ID
     * @param {eventName}:事件描述
     * @return:
     */
    mobileAgent.onStatisticsEvent = function(eventId,eventName) {
        _postMessage(
            'onStatisticsEvent',
            {
                eventId: eventId,
                eventName: eventName
            }
        );
    };


    /**
     * @description: 刷新导航栏右侧功能按钮
     * @param {appViewConfigureObj}:APP页面配置对象，详见mobile_agent_config.js
     * @return:
     */
    mobileAgent.reloadNavBarRightButtons = function(appViewConfigureObj){
        _postMessage(
            "reloadNavBarRightButtons",
            {
                configure:appViewConfigureObj
            }
        );
    };

    /**
     * @description: 日期选择控件，提供给JS使用Native样式的日期选择控件来选择日期
     * @param {format} :日期格式，yyyy-MM-dd，yyyy-MM
     * @param {startDate}:开始日期
     * @param {callBack}:回调函数
     * @return: 无
     */
    mobileAgent.showTimePicker = function (format, startDate, callBack) {
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            'showTimePicker',
            {
                type: format,
                time: startDate
            },
            callBackMethodName
        );
    };


    /**
     * @description: 图片选择方式
     * @param {type}
     * @return:
     */
    var ImageSelectType = {
        UNSELECTED : 0,//未指定，此时会先让用户选择方式
        CAMERA : 1,//相机
        PHOTOALBUM : 2//相册
    };

    /**
     * @description: 选择图片并上传
     * @param {imageSelectType}:见ImageSelectType,如ImageSelectType.UNSELECTED
     * @return:
     */
    mobileAgent.selectImageAndUpload = function (imageSelectType,callBack) {
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            'image',
            {
                imageSelectType:imageSelectType
            },
            callBackMethodName
        );
    };


    //隐藏导航栏
    mobileAgent.hideNavigationBar = function () {
        _postMessage('hideNavigationBar');
    };

    //显示导航栏
    mobileAgent.showNavigationBar = function () {
        _postMessage('showNavigationBar');
    };

    /**
     * @description: 返回到历史页面
     * @param {historyURL}:历史页面URL
     * @return:
     */
    mobileAgent.back2History = function(historyURL){
        _postMessage(
            'jumpToHistory',
            {
                history:historyURL
            }
        );
    };

    /**
     * @description: 获取用户信息
     * @param {callBack} :JS回调函数.{userID:"xxxxx",phone:"xxxxx",userName:"xxxxx",token:"xxxxxxxxx"}
     * @return:
     */
    mobileAgent.getUserInfo = function(callBack){
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            "getUserInfo",
            {},
            callBackMethodName
        );
    };


    /**
     * @description: 获取定位点
     * @param {callBack}:JS回调函数.{longitude:"经度",latitude:"纬度",address:"地址名称"}
     * @return:
     */
    mobileAgent.getLocation = function(callBack){
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            "location",
            {},
            callBackMethodName
        );
    };


    /**
     * @description: 获取业务接口基地址
     * @param {callBack}:JS回调函数
     * @return:
     */
    mobileAgent.getURLHost = function(callBack){
        var callBackMethodName = 'callBack' + Math.random();
        mobileAgent[callBackMethodName] = function (err, rs) {
            callBack(err, rs);
            mobileAgent[callBackMethodName] = null;
            callBackMethodName = null;
        };
        _postMessage(
            "getHost",
            {},
            callBackMethodName
        );
    };


    /**
     * @description: 图片展示器，支持左右滑动展示和缩放
     * @param {imageArray}:图片URL数组
     * @param {selectedIndex}:初始展示的图片索引
     * @return:
     */
    mobileAgent.imageSwipper = function(imageArray,selectedIndex){
        _postMessage(
            "imgSwiper",
            {
                imageArray:imageArray,
                selectedIndex:selectedIndex
            }
        );
    };



    /**
     * @description: 显示loading动画
     * @param {type}
     * @return:
     */
    mobileAgent.showProgress = function(){
        _postMessage("showProgress");
    };

    /**
     * @description: 隐藏loading动画
     * @param {type}
     * @return:
     */
    mobileAgent.hideProgress = function(){
        _postMessage("hideProgress");
    };


    /**
     * @description: 触发JS事件，与hybrid对象搭配使用解决两个H5页面之间的传值问题。不建议显示调用此方法，而通过hybrid相关方法触发。
     * @param {event}:JS事件名
     * @param {data}:事件附带数据
     * @return:
     */
    mobileAgent.postMessage2App = function(event,data){
        _postMessage(
            "eventNotification",//方法
            {
                event:event,//事件
                data:data//事件附带的数据
            }
        )
    };

})(window.mobileAgent || {}, window);


//hybrid对象,hybrid 用于js自身使用，接收来自客户端的调用
window.hybrid = window.hybrid || {};

(function (hybrid, window) {
    hybrid._eventArray = new Array(); //事件数组
    //触发事件
    hybrid.raiseEvent = function (action, params) {
        console.log("js:执行raiseEvent:::"+action);
        for (var i in hybrid._eventArray) {
            var evt = hybrid._eventArray[i];
            if (evt != null && evt.eventName === action) {
                console.log("hit on " + evt);
                evt.callback.apply(null, [params]);
            }else{
                console.log("没找到action:"+action);
            }
        }
    };

    hybrid.addEventListener = function (eventName, callback) {
        hybrid._eventArray.push({eventName: eventName, callback: callback});
    };

    hybrid.removeEventListener = function (eventName) {
        for (var i in hybrid._eventArray) {
            var evt = hybrid._eventArray[i];
            if (evt != null && evt.eventName === eventName) {
                hybrid._eventArray.splice(i, 1);
            }
        }
    };

    //发送JS事件
    hybrid.triggerEvent = function (event,data) {
        mobileAgent.postMessage2App(event,data);
    };

})(window.hybrid || {}, window);
